package com.chen.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.chen.api.RpcRequest;
import com.chen.api.RpcResolver;
import com.chen.api.RpcResponse;
import com.chen.exception.RpcException;
import org.springframework.context.annotation.Bean;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.ServiceLoader;

public class RpcInvoker {
    private RpcResolver rpcResolver;

    public RpcInvoker(RpcResolver rpcResolver){
        this.rpcResolver = rpcResolver;
    }

    public RpcResponse invoke(RpcRequest request) {
        RpcResponse response = new RpcResponse();
        String serviceClass = request.getServiceClass();

        Object service = rpcResolver.resolve(serviceClass);

        try {
            Class[] paramsTypes = new Class[request.getParams().length];
            for (int i=0;i<request.getParams().length;i++){
                paramsTypes[i] = request.getParams()[i].getClass();
            }
            Method method = service.getClass().getMethod(request.getMethod(),paramsTypes);
            Object result = method.invoke(service,request.getParams());
            response.setResult(JSON.toJSONString(result, SerializerFeature.WriteClassName));
            response.setStatus(true);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
            response.setStatus(false);
            response.setException(new RpcException(e.getMessage()));
        }

        return response;
    }

    private Method resolveMethodFromClass(Class<?> klass, String methodName) {
        return Arrays.stream(klass.getMethods()).filter(m -> methodName.equals(m.getName())).findFirst().get();
    }


}
